var API = API || {};

var sliderScrollTime = 1300;
var checkScrollTime = 1300;
var dropScrollTime = 500;
var delayTime = 70;
/*
 * Facilities & Services
 */
//var log = console.log;
API.Filter = {
    Data: {
        facility_id: new Array(),
        price_id: new Array(),
        stars_id: new Array(),
        distances_sea_id: new Array(),
        distances_center_id: new Array(),
        facility_item: new Array(),
        price_item: new Array(),
        stars_item: new Array(),
        distances_sea_item: new Array(),
        distances_center_item: new Array(),
        listElems: new Array(),
        sortBy: 'recommended'
    },
    Section: {
        Facility: function() {

            API.Filter.Data.facility_id = new Array();
            $.each(items, function(n, item) {   // idemo kroz objekte

                var count_item = API.Filter.Data.facility_item.length; // broji duzinu ukljucenih filtera
                var cnt = 0; // brojac pronadjenih filtera

                if ((typeof this.all_attributes !== 'undefined') && (this.all_attributes !== null)) {

                    $.each(this.all_attributes, function(attribute_id, n) {   // idemo kroz pripremljene atribute

                        $.each(API.Filter.Data.facility_item, function(n, item_id) {    // idemo kroz ukljucene filter atribute

                            if (attribute_id === item_id)
                                cnt++;
                        });
                    });
                    if (count_item === cnt) {
                        API.Filter.Data.facility_id.push(parseInt(item.object_ID));
                        //log('PUSH');
                    }

                }
            });
        },
        Price: function() {     // Bilo koja vrijednost iz price_item ako je nadjena, ukljucujemo taj objekat

            API.Filter.Data.price_id = new Array();
            cnt = 0;
            $.each(items, function(n, item) { // idemo kroz objekte

//            if (cnt == 4)
//                return;
//
//            cnt++;

                var OBJECT_FOUND = false;
                $.each(API.Filter.Data.price_item, function(n, rng) { // idemo kroz price range

                    if (!OBJECT_FOUND) {    // ovo koristimo umjesto izlaska break 2;

                        var prc_range = rng.split(",");
                        if (prc_range[1] === '-1')
                            prc_range[1] = 999999;
                        if (!preview) {

//                                log('not_preview')

                            $.each(item.rooms, function(n, room) { // idemo kroz sobe

                                var price = parseFloat(room.selling_price);
                                if ((price >= prc_range[0]) && (price < prc_range[1])) {

                                    API.Filter.Data.price_id.push(parseInt(item.object_ID));
                                    OBJECT_FOUND = true;
                                    return false; // ovdje izlazimo iz soba

                                }

                            });
                        } else {

//                                log('is_preview')


                            var price = parseFloat(item.lowest_price);
                            if ((price >= prc_range[0]) && (price < prc_range[1])) {

                                API.Filter.Data.price_id.push(parseInt(item.object_ID));
                                OBJECT_FOUND = true;
                                return false; // ovdje izlazimo iz soba

                            }

                        }
                    }

                });
            });
        },
        Stars: function() {

            API.Filter.Data.stars_id = new Array();
            $.each(items, function(n, item) { // idemo kroz objekte

                if (item.object_number_of_stars == "")
                    item.object_number_of_stars = 0;
                $.each(API.Filter.Data.stars_item, function(n, star) { // idemo kroz stars_item

                    if (star == item.object_number_of_stars) {
                        API.Filter.Data.stars_id.push(parseInt(item.object_ID));
                        return false; // ovdje izlazimo iz stars_item
                    }

                });
            });
        },
        Distances: function(attribute, distance) {

            if (attribute === 'object_distance_from_the_sea') {
                API.Filter.Data.distances_sea_id = new Array();
            } else {
                API.Filter.Data.distances_center_id = new Array();
            }

            $.each(items, function(n, item) { // idemo kroz objekte

                if (item[attribute] === "")
                    item[attribute] = 999999;
                if (parseInt(distance) >= parseInt(item[attribute])) {

                    if (attribute === 'object_distance_from_the_sea') {
                        API.Filter.Data.distances_sea_id.push(parseInt(item.object_ID));
                    } else {
                        API.Filter.Data.distances_center_id.push(parseInt(item.object_ID));
                    }
                }
            });
        }
    },
    doFilter: function(category, active, id) {

        switch (category) {

            case 'filter_facilities':

                if (active) {
                    API.Filter.Data.facility_item.push(id);
                } else {

                    API.Filter.Data.facility_item.splice($.inArray(id, API.Filter.Data.facility_item), 1);
                }

                if (API.Filter.Data.facility_item.length > 0) {
                    API.Filter.Section.Facility();
                } else {
                    API.Filter.Data.facility_id = new Array();
                }

                break;
            case 'filter_price':

                if (active) {
                    API.Filter.Data.price_item.push(id);
                } else {
                    API.Filter.Data.price_item.splice($.inArray(id, API.Filter.Data.price_item), 1);
                }

                if (API.Filter.Data.price_item.length > 0) {
                    API.Filter.Section.Price();
                } else {
                    API.Filter.Data.price_id = new Array();
                }

                break;
            case 'filter_stars':

                if (active) {
                    API.Filter.Data.stars_item.push(id);
                } else {
                    API.Filter.Data.stars_item.splice($.inArray(id, API.Filter.Data.stars_item), 1);
                }

                if (API.Filter.Data.stars_item.length > 0) {
                    API.Filter.Section.Stars();
                } else {
                    API.Filter.Data.stars_id = new Array();
                }

                break;
            case 'beach_distance':

                if (active) {
                    API.Filter.Data.distances_sea_item[0] = id;
                    API.Filter.Section.Distances('object_distance_from_the_sea', API.Filter.Data.distances_sea_item[0]);
                } else {
                    API.Filter.Data.distances_sea_id = new Array();
                    API.Filter.Data.distances_sea_item = new Array();
                }

                break;
            case 'center_distance':

                if (active) {
                    API.Filter.Data.distances_center_item[0] = id;
                    API.Filter.Section.Distances('object_distance_from_the_center', API.Filter.Data.distances_center_item[0]);
                } else {
                    API.Filter.Data.distances_center_id = new Array();
                    API.Filter.Data.distances_center_item = new Array();
                }

                break;
        }   // end switch

        API.Filter.DoAllArrays();
    },
    DoAllArrays: function() {

        var all_id = [API.Filter.Data.facility_id, API.Filter.Data.price_id, API.Filter.Data.stars_id, API.Filter.Data.distances_sea_id, API.Filter.Data.distances_center_id];
        var all_item = [API.Filter.Data.facility_item, API.Filter.Data.price_item, API.Filter.Data.stars_item, API.Filter.Data.distances_sea_item, API.Filter.Data.distances_center_item];
        var selected = new Array();
        var final = new Array();
        _.each(all_item, function(arr, index) {

            if (arr.length > 0)
                selected.push(all_id[index]);
        });
        if (selected.length > 1) {
//            log('intersection')
            final = _.intersection.apply(_, selected);
        } else if (selected.length === 1) {
//            log('equals');
            final = selected[0];
        } else {
            final = new Array();
        }

        var myItems = new Array();
        if (selected.length > 0) {

            $('#list li').remove();

            $.each(items, function(i, item) { // idemo kroz objekti niz

                var ID = parseInt(item.object_ID);

                if ($.inArray(ID, final) !== -1) {
                    myItems.push(item);
                }

            });

        } else {
//            $('#list').html(API.Filter.Data.listElems);
            myItems = items.slice(0);
        }

        var sortBy = $('#sort_by').val();

        switch (sortBy) {

            case 'price':

                myItems.sort(function(a, b) {
                    return a.sort_price - b.sort_price;
                });

                break;

            case 'recommended':

                myItems.sort(function(a, b) {
                    return a.object_search_priority - b.object_search_priority;
                });

                break;

            case 'number_of_stars':
                myItems.sort(function(a, b) {
                    return a.object_number_of_stars - b.object_number_of_stars;
                });

                break;

            case 'object_name':
                myItems.sort(function(a, b) {
                    var x = a.object_name.substr(0, 1).toLowerCase();
                    var y = b.object_name.substr(0, 1).toLowerCase();
                    return x < y ? -1 : x > y ? 1 : 0;
                });

                break;

        }

        $.each(myItems, function(i, item) { // idemo kroz objekti niz

            var ID = parseInt(item.object_ID);

            $('#list').append(API.Filter.Data.listElems[ID]);
        });

        $('.hotels-count').text($('#list li').length);
        API.imagePreview();
//        API.Pager.init();

    },
    Init: function() {

        $("#list li").each(function(index, value) {
            var ID = $(this).attr('data-id');
            API.Filter.Data.listElems[ID] = value;
        });

        $('.filterelement').on('click', function() {

            if ($("#list").isMasked()) {
                return false;
            }

            $("#list").mask(lang['filter.filtering'] + "...");
            if ($(this).hasClass('inactive')) {
                $(this).removeClass('inactive');
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
                $(this).addClass('inactive');
            }
            ;
            var category = $(this).attr('data-category');
            var active = $(this).hasClass('active');
            var id = $(this).attr('data-id');
            function action_delay() {

                API.Filter.doFilter(category, active, id);
                $("#list").unmask();
            }

            var randomnumber = delayTime + Math.floor(Math.random() * 501);
            $.scrollTo('.hotels-list', checkScrollTime, {onAfter: function() {

                    window.setTimeout(function() {
                        action_delay();
                    }, randomnumber);
                    return false;
                }});

        });
        if ($(window).width() > 900) {

            var height = $('.mask-height').height();
            $('.results-holder').height(height);
            $('#list').height(height);
        }

        $('#sort_by').on('change', function() {

            if ($("#list").isMasked()) {
                return false;
            }

            $("#list").mask(lang['filter.filtering'] + "...");

            function action_delay() {

                API.Filter.DoAllArrays();
                $("#list").unmask();
            }

            var randomnumber = delayTime + Math.floor(Math.random() * 501);
            $.scrollTo('.hotels-list', dropScrollTime, {onAfter: function() {

                    window.setTimeout(function() {
                        action_delay();
                    }, randomnumber);
                    return false;
                }});


        });

//        $('.collapse-filter').multiAccordion({
//            active: [0, 1, 2, 3],
//            click: function(event, ui) {
//                //console.log('clicked')
//            },
//            init: function(event, ui) {
//                //console.log('whoooooha')
//            },
//            tabShown: function(event, ui) {
//                //console.log('shown')
//            },
//            tabHidden: function(event, ui) {
//                //console.log('hidden')
//            }
//        });
//
//        $('.collapse-filter').multiAccordion("option", "active", [0, 1, 2, 3]);

    },
    Slider: {
        Init: function() {

            $(".slider").slider({
                animate: true,
                range: "min",
                value: 0,
                min: 0,
                max: 200,
                step: 50,
                change: API.Filter.Slider.Change

            });
        },
        Change: function(event, ui) {

//                log('SliderChange');

            var data_id = $(this).attr('data-id');
            $("#list").mask(lang['filter.filtering'] + "...");
            var value = API.Filter.Slider.UIValue(ui.value);
            $("#" + data_id).html(value);
            function action_delay() {

                API.Filter.doFilter(data_id, value, value);
                $("#list").unmask();
            }

            var randomnumber = delayTime + Math.floor(Math.random() * 501);
            $.scrollTo('.hotels-list', sliderScrollTime, {onAfter: function() {

                    window.setTimeout(function() {
                        action_delay();
                    }, randomnumber);
                    return false;
                }});
        },
        UIValue: function(value) {

            switch (value) {
                case 0:
                    return 0;
                case 50:
                    return 100;
                case 100:
                    return 300;
                case 150:
                    return 500;
                case 200:
                    return 1000;
            }

        }

    }
};
$(function() {
    $(window).load(function() {
        API.Filter.Init();
        API.Filter.Slider.Init();
//        API.Pager.init();
    });
    
});